/* cmdbuf.c */

#include "cmdbuf.h"
#include <ctype.h>

static void append_char(cmd_buf_t *buf, int ch){
	if(buf->len < CMD_BUF_CAP){
		buf->cmd[buf->len++] = (char)ch;
		buf->cmd[buf->len] = '\0';
	}
}

static void append_num(cmd_buf_t *buf, int num){
	buf->arg_value = buf->arg_value *10 + num;
}

int cmd_buf_add_key(cmd_buf_t * buf, int key){
	if(isprint(key) && !isdigit(key)){
		append_char(buf, key);
		return 0;
	}else if(isdigit(key)){
		if(buf->len != 0){
			cmd_buf_reset(buf);
			append_num(buf,key-'0');
			return -1;
		}else{
			append_num(buf, key-'0');
			return -1;
		}
	}else{
		cmd_buf_reset(buf);
		return -1;
	}		
}

int cmd_buf_reset(cmd_buf_t *buf){
	buf->cmd[0] = '\0';
	buf->arg_value = 0;
	buf->len =0;
	return 0;
}
